<?php

namespace App\Services;

use common\utils\SysCode;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Auth;
use common\utils\GoogleAuthenticator;

//帮助公告service
class AuthService
{
    /**
     * 验证谷歌码
     * @param $secret
     * @param $code
     * @param $userName
     * @return array
     */
    public static function verifyGoogleAuth($secret, $code, $userName = '')
    {
        $ga = new GoogleAuthenticator();
        $result = $ga->verifyCode($secret, $code, 1);
        //验证失败
        if (!$result && $userName) {
            self::limitGoogleAuthTimes($userName);
        }
        if(!$result){
            error_exit(SysCode::USER_GOOGLE_CODE_INVALID);
        }
        return true;
    }

    /**
     * 限制用户30秒只能错误5次
     * @param $userName
     * @param int $limit
     * @param int $duration
     * @return array
     */
    public static function limitGoogleAuthTimes($userName, $limit = 5, $duration = 30)
    {
        $key = 'google.auth.key' . $userName;
        $times = Redis::get($key);
        if ($times && $times >= $limit) {
            error_exit(SysCode::USER_GOOGLE_LOGIN_FAILED_TIMES);
        }
        if ($times) {
            Redis::set($key, $times + 1, $duration);
        } else {
            Redis::set($key, 1, $duration);
        }
        return true;
    }

    /**
     * 获取谷歌身份验证器信息
     * @param $title
     * @param $params
     * @return array
     */
    public static function getGoogleAuth($title, $params)
    {
        $user = Auth::user();
        $ga = new GoogleAuthenticator();
        $secret = $ga->createSecret(32);
        $ret = $ga->getQRCodeGoogleUrl($user['username'], $secret, $title, $params);
        $qrCodeUrl = $ret['url'];
        $codeData = $ret['data'];
        return compact('secret', 'qrCodeUrl', 'codeData');
    }


}
